package com.pay.online.online_pay.wxpay

import android.content.Intent
import com.pay.online.online_pay.OnlinePayPlugin
import com.pay.online.online_pay.provider.ContextProvider
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

internal class WechatPay private constructor() {

    companion object {

        private var wechatPay: WechatPay? = null

        @JvmStatic
        fun getInstance(): WechatPay? {
            if (wechatPay == null) {
                synchronized(WechatPay::class.java) {
                    wechatPay = WechatPay()
                }
            }
            return wechatPay
        }
    }

    private val wxApi by lazy {
        if (OnlinePayPlugin.wxAppId.isNullOrEmpty())
            throw Exception("错误：OnlinePayPlugin未设置微信支付ID")
        WXAPIFactory.createWXAPI(ContextProvider.getContextInstance(), OnlinePayPlugin.wxAppId, false)
            .apply { registerApp(OnlinePayPlugin.wxAppId) }
    }

    /** 微信APP是否已经安装 **/
    val isWXAppInstalled: Boolean by lazy { wxApi?.isWXAppInstalled ?: false }

    /**
     * 发送支付请求
     * @param params 支付请求参数
     */
    fun startPay(params: WechatPayParams) {
        wxApi?.sendReq(PayReq().apply {
            appId = params.appId
            partnerId = params.partnerId
            prepayId = params.prepayId
            packageValue = params.packageValue
            nonceStr = params.nonceStr
            timeStamp = params.timeStamp
            sign = params.sign
        })
    }

    /**
     * 回调，需要在WxEntryActivity中调用
     * @param intent
     * @param handler
     */
    fun handleIntent(
        intent: Intent?,
        handler: IWXAPIEventHandler
    ) = wxApi?.handleIntent(intent, handler)

}